//
//  HTViewController.swift
//  home
//
//  Created by Yun Zeng on 2019/9/24.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit


class HTViewController1: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hex: "efefef")
        
        let chart = HTChartView(frame: .zero)
        self.view.addSubview(chart)
        
        chart.translatesAutoresizingMaskIntoConstraints = false
        chart.heightAnchor.constraint(equalToConstant: 258).isActive = true
        chart.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 12).isActive = true
        chart.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -12).isActive = true
        chart.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
    }
}

// MARK: - 温湿度统计图
fileprivate class HTChartView: UIView {
    
    private let padding: CGFloat = 19.0

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.layer.cornerRadius = 8
        self.backgroundColor = UIColor.white
        self.translatesAutoresizingMaskIntoConstraints = false
        self.heightAnchor.constraint(equalToConstant: 258).isActive = true
        
        let topDiv = UIView()
        self.addSubview(topDiv)
        topDiv.translatesAutoresizingMaskIntoConstraints = false
        topDiv.heightAnchor.constraint(equalToConstant: 0.5).isActive = true
        topDiv.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        topDiv.topAnchor.constraint(equalTo: self.topAnchor, constant: 29.5).isActive = true
        topDiv.backgroundColor = UIColor(hex: "D4D4D4")
        
        let bottomDiv = UIView()
        self.addSubview(bottomDiv)
        bottomDiv.translatesAutoresizingMaskIntoConstraints = false
        bottomDiv.heightAnchor.constraint(equalToConstant: 0.5).isActive = true
        bottomDiv.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        bottomDiv.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -27.5).isActive = true
        bottomDiv.backgroundColor = UIColor(hex: "D4D4D4")
        
       let attributes: [NSAttributedString.Key : Any] = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular),
                NSAttributedString.Key.kern: -0.47,
                NSAttributedString.Key.foregroundColor: UIColor(hex: "5F5F5F")]
        
        let date = UILabel()
        date.attributedText = NSAttributedString(string: "10月6日", attributes: attributes)
        self.addSubview(date)
        date.translatesAutoresizingMaskIntoConstraints = false
        date.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: self.padding).isActive = true
        date.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
        date.textAlignment = .left
        date.autoresizingMask = .flexibleWidth
        
        let average = UILabel()
        average.attributedText = NSAttributedString(string: "平均: 25.5°", attributes: attributes)
        self.addSubview(average)
        average.translatesAutoresizingMaskIntoConstraints = false
        average.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -self.padding).isActive = true
        average.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
        average.textAlignment = .right
        average.autoresizingMask = .flexibleWidth
        
        Logger.Info("width: \(self.frame.width)")
        
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .equalSpacing
        stackView.alignment = .center
        stackView.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(stackView)
        stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10).isActive = true
        stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true
        stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -8).isActive = true
        
        for index in 0 ... 12 {
            let label = UILabel()
            label.widthAnchor.constraint(equalToConstant: 18.0).isActive = true
            label.heightAnchor.constraint(equalToConstant: 14).isActive = true
            label.attributedText = NSAttributedString(string: String(format: "%d", index * 2), attributes: attributes)
//            label.layer.borderColor = UIColor.blue.cgColor
//            label.layer.borderWidth = 0.5
            label.textAlignment = .center
            stackView.addArrangedSubview(label)
        }
        
        
        // 黄线
        let yellowLine = UIView()
        yellowLine.translatesAutoresizingMaskIntoConstraints  = false
        self.addSubview(yellowLine)
        
        yellowLine.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 19).isActive = true
        yellowLine.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -19).isActive = true
        yellowLine.heightAnchor.constraint(equalToConstant: 0.8).isActive = true
        yellowLine.backgroundColor = UIColor(hex: "FFB400")
        yellowLine.topAnchor.constraint(equalTo: self.topAnchor, constant: 98).isActive = true
        
        let label = UILabel()
        label.attributedText = NSAttributedString(string: "26", attributes: attributes)
        self.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.trailingAnchor.constraint(equalTo: yellowLine.leadingAnchor, constant: -1).isActive = true
        label.centerYAnchor.constraint(equalTo: yellowLine.centerYAnchor).isActive = true
        label.autoresizingMask = .flexibleWidth
        
        let greenLine = UIView()
        greenLine.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(greenLine)
        
        greenLine.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 19).isActive = true
        greenLine.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -19).isActive = true
        greenLine.heightAnchor.constraint(equalToConstant: 0.8).isActive = true
        greenLine.backgroundColor = UIColor(hex: "3CFF25")
        greenLine.topAnchor.constraint(equalTo: self.topAnchor, constant: 138).isActive = true
        
        let label1 = UILabel()
        label1.attributedText = NSAttributedString(string: "16", attributes: attributes)
        self.addSubview(label1)
        label1.translatesAutoresizingMaskIntoConstraints = false
        label1.trailingAnchor.constraint(equalTo: greenLine.leadingAnchor, constant: -1).isActive = true
        label1.centerYAnchor.constraint(equalTo: greenLine.centerYAnchor).isActive = true
        label1.autoresizingMask = .flexibleWidth
        
        let chart = ChartView()
        chart.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(chart)
        chart.topAnchor.constraint(equalTo: self.topAnchor, constant:  30).isActive = true
        chart.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -28).isActive = true
        chart.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 19).isActive = true
        chart.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -19).isActive = true
        chart.backgroundColor = UIColor.clear
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension CGPoint {
    func toRect(rect: CGRect) -> CGPoint {
        return CGPoint(x: self.x * rect.width, y: (1 - self.y) * rect.height)
    }
}


fileprivate class ChartView: UIView {
    
    var entries = [CGPoint]()
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        if self.entries.isEmpty {
            return
        }
        
        let pathStroke = UIBezierPath()
        pathStroke.move(to: self.entries.first!.toRect(rect: rect))
        for i in 1 ..< self.entries.count {
            pathStroke.addLine(to: self.entries[i].toRect(rect: rect))
        }
        pathStroke.addLine(to: self.entries.last!.toRect(rect: rect))
        UIColor(hex: "0098FF").setStroke()
        pathStroke.lineWidth = 1.5
        pathStroke.lineCapStyle = .round
        pathStroke.lineJoinStyle = .round
        pathStroke.stroke()
        
        let path = UIBezierPath()
        path.move(to: self.entries.first!.toRect(rect: rect))
        for i in 1 ..< self.entries.count {
            path.addLine(to: self.entries[i].toRect(rect: rect))
        }
        path.addLine(to: CGPoint(x: rect.width, y: rect.height))
        path.addLine(to: CGPoint(x: 0, y: rect.height))
        path.close()

        let gradient = CGGradient(
            colorsSpace: nil,
            colors: [
                UIColor(hex: "0098FF").cgColor,
                UIColor(hex: "ffffff", alpha: 0.000).cgColor] as CFArray,
            locations: [0, 1])!


        path.usesEvenOddFillRule = true
        let context = UIGraphicsGetCurrentContext()!
        context.saveGState()
        path.addClip()
        context.drawLinearGradient(gradient,
                                   start: CGPoint(x: 0, y: 0),
                                   end: CGPoint(x: 0, y: rect.height - 30),
                                   options: .drawsAfterEndLocation)
        context.restoreGState()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        guard let statistics = CharacteristicStatistics(data: TemperatureData) else {
            return
        }
        self.entries = statistics.entries
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



// MARK: -配件属性记录统计分析
fileprivate class CharacteristicStatistics {
    
    struct Records: Codable {
        var aid: String
        var sid: Int
        var cid: Int
        var before: String
        var after: String
        struct Record: Codable {
            var time: String
            var value: AnyJSONType
        }
        var logs: [Record]
    }
    
    var entries = [CGPoint]()
    var average: Float = 0
    
    init? (data: Data) {
        guard let msg = try? JSONDecoder().decode(Records.self, from: data) else {
            return nil
        }
        
        if msg.logs.isEmpty {
            return nil
        }
        
        var logs = msg.logs
        // 其实时间是否有值
        if logs.first!.time != msg.after {
            logs.insert(Records.Record(time: msg.after, value: logs.first!.value), at: 0)
        }
        // 结束时间是否有值
        if logs.last!.time != msg.before {
            logs.append(Records.Record(time: msg.before, value: logs.last!.value))
        }
    
        // 计算平均值
        for i in 1 ..< logs.count {
            let interval = logs[i].time.toDate().timeIntervalSince(logs[i-1].time.toDate())
            average += Float(interval) * (logs[i].value.toValueFloat()! + logs[i-1].value.toValueFloat()!) / 2
        }
        let interval = logs.last!.time.toDate().timeIntervalSince(logs.first!.time.toDate())
        average = average / Float(interval)
        
        let height: Float = 40.0
        let tStart = msg.after.toDate()
        for i in 0 ..< logs.count {
            let xp = logs[i].time.toDate().timeIntervalSince(tStart) / interval
            let yp = (logs[i].value.toValueFloat()! - 0) / height
            self.entries.append(CGPoint(x: xp, y: Double(yp)))
        }
    }
}


// MARK: - 温度数据
fileprivate let TemperatureData = """
{"after":"2019-10-05 14:30:28","aid":"00158d0002379233","before":"2019-10-06 14:30:28","cid":1,"limit":0,"logs":[{"time":"2019-10-05 14:59:38","value":27.2},{"time":"2019-10-05 15:44:44","value":27.71},{"time":"2019-10-05 16:40:59","value":28.09},{"time":"2019-10-05 16:41:04","value":28.24},{"time":"2019-10-05 16:41:10","value":28.33},{"time":"2019-10-05 16:41:30","value":28.43},{"time":"2019-10-05 16:55:34","value":27.89},{"time":"2019-10-05 20:14:08","value":27.37},{"time":"2019-10-05 20:19:09","value":26.85},{"time":"2019-10-05 20:26:22","value":26.32},{"time":"2019-10-05 20:34:34","value":25.75},{"time":"2019-10-05 20:47:53","value":25.25},{"time":"2019-10-05 21:04:29","value":24.71},{"time":"2019-10-05 22:03:37","value":24.2},{"time":"2019-10-06 03:31:58","value":23.88},{"time":"2019-10-06 07:19:32","value":24.11},{"time":"2019-10-06 08:00:40","value":24.61},{"time":"2019-10-06 08:11:34","value":25.12},{"time":"2019-10-06 08:18:16","value":25.44},{"time":"2019-10-06 08:31:05","value":25.99},{"time":"2019-10-06 09:23:21","value":26.5},{"time":"2019-10-06 09:30:53","value":27.01},{"time":"2019-10-06 09:47:39","value":27.51},{"time":"2019-10-06 10:23:14","value":28.06},{"time":"2019-10-06 11:20:56","value":27.56},{"time":"2019-10-06 11:41:38","value":27.01},{"time":"2019-10-06 11:56:38","value":26.51},{"time":"2019-10-06 12:03:40","value":26},{"time":"2019-10-06 12:12:53","value":25.5},{"time":"2019-10-06 12:24:26","value":25},{"time":"2019-10-06 12:45:08","value":24.78},{"time":"2019-10-06 12:54:06","value":25.3},{"time":"2019-10-06 13:04:39","value":25.81},{"time":"2019-10-06 13:17:38","value":26.32},{"time":"2019-10-06 13:49:13","value":26.84},{"time":"2019-10-06 14:13:51","value":27.34}],"sid":1}
""".data(using: .utf8)!


fileprivate let HumidityData = """
{"after":"2019-10-05 14:30:28","aid":"00158d0002379233","before":"2019-10-06 14:30:28","cid":2,"limit":0,"logs":[{"time":"2019-10-05 14:59:38","value":66},{"time":"2019-10-05 15:44:44","value":65},{"time":"2019-10-05 16:40:59","value":77},{"time":"2019-10-05 16:41:04","value":84},{"time":"2019-10-05 16:41:10","value":77},{"time":"2019-10-05 16:41:15","value":71},{"time":"2019-10-05 16:41:30","value":65},{"time":"2019-10-05 16:55:34","value":63},{"time":"2019-10-05 20:14:08","value":58},{"time":"2019-10-05 20:19:09","value":53},{"time":"2019-10-05 20:26:22","value":50},{"time":"2019-10-05 20:34:34","value":48},{"time":"2019-10-05 20:47:53","value":47},{"time":"2019-10-05 21:04:29","value":48},{"time":"2019-10-05 22:03:37","value":49},{"time":"2019-10-06 03:31:58","value":55},{"time":"2019-10-06 07:19:32","value":61},{"time":"2019-10-06 08:00:40","value":60},{"time":"2019-10-06 08:11:34","value":62},{"time":"2019-10-06 08:18:16","value":68},{"time":"2019-10-06 08:31:05","value":72},{"time":"2019-10-06 09:23:21","value":71},{"time":"2019-10-06 09:30:53","value":70},{"time":"2019-10-06 09:47:39","value":68},{"time":"2019-10-06 10:23:14","value":66},{"time":"2019-10-06 11:20:56","value":63},{"time":"2019-10-06 11:41:38","value":64},{"time":"2019-10-06 11:56:38","value":58},{"time":"2019-10-06 12:03:40","value":53},{"time":"2019-10-06 12:12:53","value":51},{"time":"2019-10-06 12:24:26","value":49},{"time":"2019-10-06 12:45:08","value":55},{"time":"2019-10-06 12:54:06","value":56},{"time":"2019-10-06 13:04:40","value":59},{"time":"2019-10-06 13:17:38","value":60},{"time":"2019-10-06 13:49:13","value":64}],"sid":1}
""".data(using: .utf8)!

